package com.bantang.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.nio.charset.StandardCharsets;

public class Consumer {

    private final static String QUEUE_NAME = "hello2";

    private static StringRedisTemplate stringRedisTemplate;

    public static void main(String[] argv) throws Exception {


        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.56.101");
        Connection connection = factory.newConnection();

        for (int i = 0; i < 2; i++) {
            Channel channel = connection.createChannel();

            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

            channel.basicQos(1);
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);

                try {

                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                    Thread.sleep(10000);
                    System.out.println(" [x] Received '" + message + "'");
                } catch (InterruptedException e) {
                    channel.basicNack(delivery.getEnvelope().getDeliveryTag(),false,true);
                    e.printStackTrace();
                }finally {
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                }

            };

            channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> { });
        }
    }
}